from flask import Blueprint,request,jsonify
import re
# 密码加密
from werkzeug.security import generate_password_hash,check_password_hash
from conf.comm import sqlalchemy_context
from database import *
import json
#蓝图初始化
bp_users = Blueprint('users',__name__)
#注册功能实现
@bp_users.route('/reg',methods=['POST'])
@sqlalchemy_context()
def reg():
    # 获取vue传过来的信息的信息  获取列表
    gain = request.data
    print(gain)
    # 判断获没获取出来是否为空
    if not gain:
        # 如果data没有获取出来就用form获取出来  获取单个数据
        gain = request.form
    else:
        # 获取出来之后json封装
        gain = json.loads(gain)
    # 有效性验证  使用正则验证手机号
    reg = re.match('^1[3-9]\d{9}$',gain['mobile'])
    if reg:
        return jsonify({"code":10012,'mes':'手机号不合法'})
    # 构造user
    try:
        # 填写用户名和密码
         user = User(username=gain['username'],password=generate_password_hash(gain['password']),mobile=gain['mobile'])
         # 添加
         db.session.add(user)
         # 保存
         db.session.commit()
         return jsonify({"code":200})
    except:
        return jsonify({"code":10010})

import random
from utils.redisconn import r
from conf.comm import send_message
#发送验证码
@bp_users.route('/login',methods=['POST','GET'])
@sqlalchemy_context()
def login():
    if request.method == 'POST':
        data = json.loads(request.data)
        mobile = data['mobile']
        if not mobile:
            return jsonify({'code':20010,'mes':'必须输入正确的手机号'})
        codes = r.get_str(mobile)
        if codes:
            return jsonify({'code':20011,'mes':'60秒内不能再发了'})

        #生成6位数
        code = random.randint(100000, 999999)
        flag = send_message(mobile, code, 1)
        if flag:
            r.set_str(mobile,code,60)
            return jsonify({'code':200,'codes':code})
        else:
            return jsonify({'code':20012,'mes':"发送失败"})

#用户名密码登录
@bp_users.route('/login1',methods=['POST','GET'])
@sqlalchemy_context()
def login1():
    data=json.loads(request.data)
    username = data['username']
    password = data['password']
    user = User.query.filter_by(username=username).first()
    if user:
        if check_password_hash(user.password,password):
            return jsonify({'code':200,'userid':user.id})
        else:
            return jsonify({'code':20014,'mes':'密码错误'})
    else:
        return jsonify({'code':20015,'mes':'用户名错误'})



#手机号登录
@bp_users.route('/login2',methods=['POST'])
@sqlalchemy_context()
def login2():
    data = json.loads(request.data)
    mobile = data['mobile']
    codes = data['codes']
    code = r.get_str(mobile)
    if str(codes) == (code):
        return jsonify({'code':200})
    else:
        return jsonify({'code':20013})
